<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\Product as ProductModel;
use app\common\model\Store as StoreModel;
use app\common\model\Car as CarModel;
use app\common\model\Violation as ViolationModel;
use app\common\model\ViolationLog as ViolationLogModel;
use think\Db;
use think\Validate;
use app\common\library\Upload;
class Index extends Api
{
    protected $noNeedLogin = 'lookstore,register,getopenid,getjs,getTicket,upload_pic,getAccessToken,createNoncestr';
    protected $noNeedRight = ['*'];

    /**
     * 首页接口
     * @path api/index/index
     */
    public function index()
    {
        $userId = $this->auth->id;
        //公司数量
        $data['store_count']=StoreModel::count();
        //车辆数量
        $data['car_count']=CarModel::where(['is_del'=>0])->count();
        //项目待审核数量
        $data['product_count']=ProductModel::where(['is_del'=>0,'status'=>1])->count();
        $this->success('请求成功',$data);
    }


    /*
     * 项目列表
     * @path api/index/getproduct
     * */
    public function getproduct()
    {
        $user_id = $this->auth->id;
        $user = $this->auth->getUser();
        $page = $this->request->param("page",1);
        $keywords = $this->request->param("keywords");
        $car_id = $this->request->param("car_id");

        $list = ProductModel::get_list($page,$keywords,$car_id);
        $this->success("请求成功",$list);
    }

    /*
     * 项目详情
     * @path api/index/getproductinfo
     * */
    public function getproductinfo()
    {
        $id = $this->request->param("id",'');
        $user_id = $this->auth->id;
        if(!$id){
            $this->error("项目id不能为空");
        }
        $info = ProductModel::get_info($id);
        $this->success("请求成功",$info);
    }

    /*
     * 车辆列表
     * @path api/index/getcar
     * */
    public function getcar()
    {
        $user_id = $this->auth->id;
        $user = $this->auth->getUser();
        $page = $this->request->param("page",1);
        $keywords = $this->request->param("keywords");
        $product_id = $this->request->param("product_id");
        $list = CarModel::get_list($page,$keywords,$product_id);
        $this->success("请求成功",$list);
    }

    /*
     * 车辆详情
     * @path api/index/getcarinfo
     * */
    public function getcarinfo()
    {
        $id = $this->request->param("id",'');
        $user_id = $this->auth->id;
        if(!$id){
            $this->error("车辆id不能为空");
        }
        $info = CarModel::get_info($id);
        $this->success("请求成功",$info);
    }

    /*
     * 公司列表
     * @path api/index/getproduct
     * */
    public function getcompany()
    {
        $user_id = $this->auth->id;
        $user = $this->auth->getUser();
        $page = $this->request->param("page",1);
        $keywords = $this->request->param("keywords");
      
        $list = StoreModel::get_list($page,$keywords);
        $this->success("请求成功",$list);
    }

    /*
     * 公司详情
     * @path api/index/getproductinfo
     * */
    public function getcompanyinfo()
    {
        $id = $this->request->param("id",'');
        $user_id = $this->auth->id;
        if(!$id){
            $this->error("公司id不能为空");
        }
        $info = StoreModel::get_info($id);
        unset($info['password']);
        $this->success("请求成功",$info);
    }

    /*
     * 审核项目
     * @path api/index/product_authen
     * */
    public function product_authen()
    {
        $id = $this->request->param("id",'');
        $status = $this->request->param("status",'');
        $remark = $this->request->param("remark",'');
        $user_id = $this->auth->id;
        if(!$id){
            $this->error("项目id不能为空");
        }
        $info = ProductModel::get_info($id);
        if(!$info)
        {
            //
            $this->error("项目不存在");
        }
        if($info['status']!=1)
        {
            $this->error("无需审核");
        }
        if($status==1)
        {
            //通过，变成3
            $data['status']=3;
            $data['authen_time_zj']=time();
        }
        if($status==2)
        {
            //通过，变成5
            $data['status']=5;
            $data['remark']=$remark;
        }
        Db::startTrans();
        try {
            $data['authen_time']=time();
           
            $change_info=db('change_log')->where(['type'=>'3','change_id'=>$id,'status'=>'1'])->find();
            db('change_log')->where(['id'=>$change_info['id']])->update(['status'=>$data['status']]);
            if($data['status']==3)
            {
                //如果是通过
                if(isset($change_info['change_images']) && $change_info['change_images'])
                {
                    $params['images']=$info['images'].','.$change_info['change_images'];
                }
            }
            $result=ProductModel::where(['id'=>$id])->update($data);
            if($result)
            {
                Db::commit();
                $this->success("审核成功");
            }
            else
            {
                Db::rollback();
                $this->error("审核失败");
            }
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        
    }
    /*
     * 执法记录列表
     * @path api/index/getviolation
     * */
    public function getviolation()
    {
        $user_id = $this->auth->id;
        $user = $this->auth->getUser();
        $page = $this->request->param("page",1);
        $keywords = $this->request->param("keywords");
        $vio_id = $this->request->param("vio_id");
        if($vio_id)
        {
            $list = ViolationLogModel::get_list($page,$keywords,$user_id,$vio_id);
        }
        else
        {
            $list = ViolationModel::get_list($page,$keywords,$user_id,$vio_id);
        }
        
        $this->success("请求成功",$list);
    }

    /*
     * 执法详情
     * @path api/index/getviolationinfo
     * */
    public function getviolationinfo()
    {
        $id = $this->request->param("id",'');
        $user_id = $this->auth->id;
        if(!$id){
            $this->error("执法id不能为空");
        }
        $info = ViolationModel::get_info($id);
        $this->success("请求成功",$info);
    }
    /*
     * 执法详情
     * @path api/index/getviolationinfo
     * */
    public function getviolationloginfo()
    {
        $id = $this->request->param("id",'');
        $user_id = $this->auth->id;
        if(!$id){
            $this->error("执法id不能为空");
        }
        $info = ViolationlogModel::get_info($id);
        $this->success("请求成功",$info);
    }

     /*
     * 添加执法记录
     * @path api/index/addviolation
     * */
    public function addviolation()
    {
        $car_id = $this->request->param("car_id",'');
        $is_illegal = $this->request->param("is_illegal",'');
        $content = $this->request->param("content",'');
        $pic = $this->request->param("pic",'');
        $vio_id = $this->request->param("vio_id",'');
        $edit_content = $this->request->param("edit_content",'');
        $user_id = $this->auth->id;
        if(!$car_id){
            $this->error("车辆id不能为空");
        }
       

        $carinfo=db('car')->where(['id'=>$car_id])->find();
        if(!$carinfo)
        {
            $this->error("车辆不存在");
        }
        //查询项目
        $product=db('product')->where('find_in_set('.$car_id.',car_ids)')->column('id');
        // var_dump($product);
        $productstr=implode(',',$product);
        $data['store_id']=$carinfo['store_id'];
        $data['product_ids']=$productstr;

        $data['zhifa_id']=$user_id;
        $data['car_id']=$car_id;
        $data['is_illegal']=$is_illegal;
        $data['content']=$content;
        $picarr=explode(',',$pic);
        foreach ($picarr as $key => &$value) {
            # code...
            $value=parse_url($value)["path"];
        }
        $pic=implode(',',$picarr);
        $data['pic']=$pic;
        $data['edit_content']=$edit_content;
        //判断是添加还是修改
        if($vio_id)
        {
            //修改
            $vioinfo=db('violation')->where(['id'=>$vio_id])->find();
            if(!$vioinfo)
            {
                $this->error("记录不存在");
            }
            $data['edit_time']=time();
            $data['is_edit']=1;
            $result=db('violation')->where(['id'=>$vio_id])->update($data);
            //填写变动记录
            unset($vioinfo['id']);
            $data['violation_id']=$vio_id;
            db('violation_log')->insert($data);
        }
        else
        {
            //添加
            $data['add_time']=time();
            $result=db('violation')->insert($data);

        }
        if($result)
        {
            $this->success("提交成功");
        }
        else
        {
            $this->error("提交失败");
        }
        
    }

    function upload_pic()
    {
        $file = $this->request->file('filePath');
        try {
            $upload = new Upload($file);
            $attachment = $upload->upload();
        } catch (UploadException $e) {
            $this->error($e->getMessage());
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success(__('Uploaded successful'), ['url' => $attachment->url, 'full_url' => cdnurl($attachment->url, true)]);
    }

    /*
     * 注册公司
     * @path api/index/register
     * */
    public function register()
    {
        $rules = [
            'store_name'=>'require',
            'address'=>'require',
            'real_address'=>'require',
            'lat'=>'require',
            'lng'=>'require',
            'zz_num'=>'require',
            'store_type'=>'require',
            'registered_price'=>'require',
            'establishment_day'=>'require',
            'name'=>'require',
            'tel'=>'require',
            'contact_name'=>'require',
            'contact_tel'=>'require',
            'start_time'=>'require',
            'end_time'=>'require',
            'registration_authority'=>'require',
            'business_scope'=>'require',
            'car_count'=>'require',
            'install_count'=>'require',
            'road_no'=>'require',
            'road_endtime'=>'require',
        ];
        $msg = [
            'store_name.require'=>"请填写公司名称",
            'address.require'=>"请填写注册详细地址",
            'real_address.require'=>"请填写实际办公地址",
            'lat.require'=>"请填写纬度",
            'lng.require'=>"请填写经度",
            'zz_num.require'=>"请填写统一社会信用代码",
            'store_type.require'=>"请填写企业类型",
            'registered_price.require'=>"请填写注册资本",
            'establishment_day.require'=>"请填写成立日期",
            'name.require'=>"请填写法定代表人",
            'tel.require'=>"请填写法人电话",
            'contact_name.require'=>"请填写负责人名称",
            'contact_tel.require'=>"请填写负责人电话",
            'start_time.require'=>"请填写营业开始时间",
            'end_time.require'=>"请填写营业截止时间",
            'registration_authority.require'=>"请填写登记机关",
            'business_scope.require'=>"请填写经营范围",
            'car_count.require'=>"请填写车辆数量",
            'install_count.require'=>"请填写安装定位及视频装置数量",
            'road_no.require'=>"请填写道路运输经营许可证号",
            'road_endtime.require'=>"请填写道路运输经营许可证有效期至",
        ];
       
        

        $data = $this->request->post();
        $validate = new Validate($rules, $msg);
        $result   = $validate->check($data);
        if (!$result) {
            $msg = $validate->getError();
            $this->error($msg);
        }
       
        $pic = $this->request->param("pic",'');
        
        $picarr=explode(',',$pic);
        foreach ($picarr as $key => &$value) {
            # code...
            $value=parse_url($value)["path"];
        }
        $pic=implode(',',$picarr);
        $data['images']=$pic;
        //判断是添加还是修改
        if(isset($data['id']))
        {
            //修改
            $info=db('store')->where(['id'=>$data['id']])->find();
            if(!$info)
            {
                $this->error("申请不存在");
            }
            $data['status']='2';
            $result=db('store')->where(['id'=>$data['id']])->update($data);
            
        }
        else
        {
            //添加
            $data['status']='2';
            $data['add_time']=time();
            $result=db('store')->insert($data);

        }
        if($result)
        {
            $this->success("提交成功");
        }
        else
        {
            $this->error("提交失败");
        }
        
    }
    /*
     * 查看申请入驻详情
     * @path api/index/lookstore
     * */
    public function lookstore()
    {
        $open_id = $this->request->param("open_id",'');
        
        if(!$open_id){
            $this->error("open_id不能为空");
        }
        $store_id=StoreModel::where(['open_id'=>$open_id])->value('id');
        $info = StoreModel::get_info($store_id);
        //获取登录密码

        $this->success("请求成功",$info);
    }
    /*
     * 获取省市区
     * @path api/index/getarea
     * */
    public function getarea()
    {
        $pid = $this->request->param("pid",'');
        
        
        if($pid)
        {
            $where['pid']=$pid;
        }
        else
        {
            $where['pid']=0;
        }
        $list=db('area')->where($where)->field('id,name')->select();
        $this->success("请求成功",$list);
    }

    function getopenid()
    {
        write_log(1111);
        $code = $this->request->param("code",'');
        $appid='';
        $secret='';
        $access_token_jilu = Db::name('weixin_config')->where('id',1)->find();
        $appid=$access_token_jilu['oaappid'];
        $secret=$access_token_jilu['oaappsecret'];
        $get_openid_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid. '&secret='.$secret.'&code=' . $code . '&grant_type=authorization_code';
        $rst = file_get_contents($get_openid_url);
        $rst = json_decode($rst, true);
        // if(isset($rst['access_token'])){
        //     // Db::name('weixin_config')->where('id',1)->update(['access_token'=>$rst['access_token'],'exp_time'=>time()]);
        // }
        write_log($rst);
        if (isset($rst['openid'])) {
            // return $rst;
            $this->success("请求成功",$rst['openid']);
        } else {
            $this->error("获取失败");
            // return false;
        }
    }
    function getjs()
    {
        $jsapiTicket = $this->getTicket();

          $url = gethost().$_SERVER['REQUEST_URI'];

          $timestamp = time();

          $nonceStr = $this->createNonceStr();

          // 这里参数的顺序要按照 key 值 ASCII 码升序排序

          $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";

          $signature = sha1($string);

          $signPackage = array(

            "nonceStr"  => $nonceStr,

            "timestamp" => $timestamp,

            "signature" => $signature,

            // "rawString" => $string

          );
          $this->success("请求成功",$signPackage);
    }
    /**

     * 获取jsapi_ticket

     */

    public function getTicket(){

        $datas=db('weixin_config')->where('id=1')->find();
        $data = json_decode($datas['ticket_json'],true);

        if($data['expires_in'] > time()){

            return $data['ticket'];

        }



        $response = json_decode(file_get_contents("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=". $this->getAccessToken() ."&type=jsapi"),true);

        $response['expires_in'] += time()-100;

        // file_put_contents("ticket.json",json_encode($response));
        db('weixin_config')->where('id=1')->update(['ticket_json'=>json_encode($response)]);

        return $response['ticket'];

    }
    /**

     * 获取access_token

     */

    public function getAccessToken(){

        $access_token_jilu = Db::name('weixin_config')->where('id',1)->find();
        
        if(time()-intval($access_token_jilu['oaexp_time'])>3600 || $access_token_jilu['oaaccess_token']==''){
            $appid = $access_token_jilu['oaappid'];
            $secret =  $access_token_jilu['oaappsecret'];
            $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$secret;
            $res = file_get_contents($url);
            var_dump($url);
            var_dump($res);die;
            $access_token = $res['access_token'];
            $update_data = [
                'oaexp_time' =>time(),
                'oaaccess_token'=>$access_token
            ];
            
            $update_data = Db::name('weixin_config')->where('id',1)->update($update_data);
            
        }else{
            $access_token = $access_token_jilu['oaaccess_token'];
            
        }
        // dump($access_token);die;
        return $access_token;

    }
   
    /**

     * 随机字符串

     */

    protected function createNoncestr( $length = 18 ){

        $time = str_replace('.','',microtime(true));

        $chars = "abcdefghijklmnopqrstuvwxyz0123456789";

        $str ="";

        for ( $i = 0; $i < $length; $i++ )  {

            $str.= substr($chars, mt_rand(0, strlen($chars)-1), 1);

        }

        return $time.$str;

    }

   
}
